package fun.werfamily.wf.base.interceptor;

import fun.werfamily.wf.base.dto.LoginUserContext;
import fun.werfamily.wf.base.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Mr.WenMing Zhang
 * @Date: 2023-04-24 21:53
 * @Description:
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static List<String> permitPathList;

    String AUTH_HEADER = "Authorization";

    static {
        permitPathList = new ArrayList<>();
        permitPathList.add("login");
        permitPathList.add("open");
        permitPathList.add("VerifyCode");
        permitPathList.add("register");
    }

    private boolean isPermit(String path){
        boolean isPermit = false;
        for (String permitPath : permitPathList) {
            if (path.contains(permitPath)) {
                isPermit = true;
                break;
            }
        }
        return isPermit;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录验证成功，放行
        //我希望在controller中直接获取用户的信息怎么获取
        String authHeader = request.getHeader(AUTH_HEADER);
        String uri = request.getRequestURI();
        if (StringUtils.isNoneEmpty(authHeader) && !isPermit(uri)){
            LoginUserContext.put(TokenUtil.parseToken(request));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删 ThreadLocal中用完的信息会有内存泄漏的风险
        LoginUserContext.remove();
    }
}
